import Vue from 'vue'
import VueRouter from 'vue-router'
import {Toast} from 'vant'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/Login.vue'),
    meta:{
      showTabbar: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/register/Register.vue'),
    meta:{
      showTabbar: false
    }
  },
  {
    path: '/video',
    name: 'Video',
    component: () => import('../views/video/Video.vue'),
    meta:{
      showTabbar: true
    }
  },
  {
    path: '/videodetail/:id',
    name: 'VideoDetail',
    component: () => import('../views/videodetail/VideoDetail.vue'),
    meta:{
      showTabbar: false
    }
  },
  {
    path: '/video/setting',
    name: 'Setting',
    component: () => import('../views/video/child/Setting.vue'),
    meta:{
      showTabbar: false
    }
  },
  {
    path: '/music',
    name: 'Music',
    component: () => import('../views/music/Music.vue'),
    meta:{
      showTabbar: true
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/profile/Profile.vue'),
    meta:{
      showTabbar: true,
      requireAuth: true
    }
  },
  {
    path: '/',
    redirect:'/video'
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if(from.name == "login"){ // 如果不需要权限校验，直接进入路由界面
    next();
  }else if(to.meta.requireAuth){
    // 判断该路由是否需要登录权限
    if (localStorage.getItem("token")) {  // 获取当前的token是否存在
      next();
    } else {
      Toast('请登录后再访问')
      next({
        path: '/login', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: {redirect: to.fullPath}
      })
    }
  }else { // 如果不需要权限校验，直接进入路由界面
    next();
  }
})

export default router
